package com.ynding.ws.endpoint;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.parsers.DocumentBuilderFactory;

import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import org.springframework.xml.xpath.Jaxp13XPathTemplate;
import org.springframework.xml.xpath.XPathOperations;

import com.ynding.ws.param.HolidayRequest;
import com.ynding.ws.param.HolidayResponse;
import com.ynding.ws.service.HumanResourceService;

@Endpoint
public class HolidayEndpoint {

	private static final String NAMESPACE_URI = "http://ynding.com/hr/schemas";
	private HumanResourceService humanResourceService;
	
//	private XPathOperations template = new Jaxp13XPathTemplate();
//	private XPathExpression<Element> startDateExpression;
//	private XPathExpression<Element> endDateExpression;
//	private XPathExpression<Element> firstNameExpression;
//	private XPathExpression<Element> lastNameExpression;
//	private final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	
	@Autowired
	public HolidayEndpoint(HumanResourceService humanResourceService) {
		this.humanResourceService = humanResourceService;
		
//		Namespace namespace = Namespace.getNamespace("hr", NAMESPACE_URI);
//		XPathFactory xPathFactory = XPathFactory.instance();
//		startDateExpression = xPathFactory.compile("//hr:StartDate", Filters.element(), null, namespace);
//		endDateExpression = xPathFactory.compile("//hr:EndDate", Filters.element(), null, namespace);
//		firstNameExpression = xPathFactory.compile("//hr:FirstName", Filters.element(), null, namespace);
//		lastNameExpression = xPathFactory.compile("//hr:LastName", Filters.element(), null, namespace);
	}
	
	@PayloadRoot(namespace=NAMESPACE_URI,localPart="HolidayRequest")
	@ResponsePayload
	public HolidayResponse handleHolidayRequest(@RequestPayload HolidayRequest request){
		
		HolidayResponse response = humanResourceService.bookHoliday(request);
		
		return response;
	}
	
	/*private Date parseDate(XPathExpression<Element> expression, Element element) throws ParseException {
		Element result = expression.evaluateFirst(element);
		if (result != null) {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			return dateFormat.parse(result.getText());
		} else {
			throw new IllegalArgumentException("Could not evaluate [" + expression + "] on [" + element + "]");
		}
	}*/
	
}
